/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package shellCommands;

import Sessions.EcomAdminRemote;
import Sessions.EcomCustomersRemote;
import entityBeans.Customers;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author SOGOBA
 */
public class CustomersCommand implements InterShell {

    ContextCommande cxtCmd;

    public CustomersCommand(ContextCommande contextCmd) {
        cxtCmd = contextCmd;
    }

    @Override
    public Commands getName() {
        return Commands.customer;
    }

    @Override
    public String getShortDescription() {
        String description = "Customer management\n";
        description += "\t  : [without args] ........................................list all customers\n";
        description += "\t  : -add [lastName] [firstName] [email] [password] [Account] [Solde] [Adresse]..create a customer\n";
        description += "\t  : -remove [customer id] ........................................delete a customer\n";
        description += "\t  : -connect [Name];[Password] ...................................connect user to the system \n";
        return description;
    }

    @Override
    public void execute(String cmd,EcomAdminRemote ecomAdmin,EcomCustomersRemote ecomCust) throws Exception {
        InitialContext sc = new InitialContext();
        //    StringBuffer res = new StringBuffer();
        EcomCustomersRemote ecomCustomerBean = (EcomCustomersRemote) sc.lookup("java:global/StoreEcom/StoreEcom-ejb/EcomCustomers");
        EcomAdminRemote ecomAdminBean = (EcomAdminRemote) sc.lookup("java:global/StoreEcom/StoreEcom-ejb/EcomAdmin");
        StringTokenizer st = new StringTokenizer(cmd, " ");

        // Ignore cmd
        st.nextToken();

        // without arg : list all accounts
        if (st.countTokens() == 0) {
            /**
             * if (true != cxtCmd.getVar("admin")) { // throw new
             * InsuffisantPrivilege();
            }*
             */
            if (cxtCmd.getVar("output").equals("XML")) {
                System.out.println(getXML(ecomAdminBean.getAllClient()));
            } else {
                System.out.println(getText(ecomAdminBean.getAllClient()));

            }
            //   String textString="";
            //    for (Customers cust : ecomAdminBean.getAllClient()){
            // textString+="Id Client :"+ cust.getIdCustomer() +"Name :"+ cust.getName()+ "FirstName :"+ cust.getFistName()+ "Adress :"+ cust.getAdress()+ "Mail : "+ cust.getMail()+ "\n";
            //   }
            //      System.out.println(textString);
            //      System.out.println(cxtCmd.getVar("output").toString());

        } // With option
        else {

            String option = st.nextToken();
            // adding
            switch (option) {
                case "-add":
                    /**
                     * if (true != context.getVar("admin")) { throw new
                     * InsuffisantPrivilege();
                     *
                     */
                    String lastName = st.nextToken();
                    String firstName = st.nextToken();
                    String mail = st.nextToken();
                    String password = st.nextToken();
                    String account = st.nextToken();
                    Double solde = Double.valueOf(st.nextToken());
                    String adress = st.nextToken();
                    ecomCustomerBean.createCust(null, lastName, firstName, mail, password, account, solde, adress);
                    //res.append(_context.returnCode("Customer Created with id #" + id, RESULT_ACTION.SUCCESS));
                    //res.append(context.returnCode("Error with Customer creation", RESULT_ACTION.FAILED));
                    break;
                case "-remove":
                    /**
                     * if (true != context.getVar("admin")) { throw new
                     * InsuffisantPrivilege(); }
                     *
                     */
                    if (st.countTokens() == 1) {
                        int id = Integer.valueOf(st.nextToken());
                        ecomCustomerBean.removeCust(id);
                        //res.append(_context.returnCode("Customer #" + id + " deleted", RESULT_ACTION.SUCCESS));
                    } else {
                        //res.append(_context.returnCode(Shell.INCORRECT_ARGS_NUMBER, RESULT_ACTION.FAILED));
                        // System.out.println(Shell.INCORRECT_ARGS_NUMBER);
                    }
                    break;
                case "-connect":
                    if (st.countTokens() == 2) {
                        String name = st.nextToken();
                        String pwd = st.nextToken();
                        ecomCustomerBean.getConnect(name, pwd);
                    }
                    break;
                case "-id":
                    if (st.countTokens() == 1) {
                        int idCust = Integer.parseInt(st.nextToken());
                         List<Customers> lesClients=new ArrayList<Customers>();
                         lesClients.add(ecomAdminBean.getClientById(idCust));
                        if (cxtCmd.getVar("output").equals("XML")) {
                           
                            System.out.println(getXML(lesClients));
                        } else {
                            System.out.println(getText(lesClients));                      
                        }
                        break;} 
                     case "-name":
                    if (st.countTokens() == 1) {
                        String name = st.nextToken();
                        if (cxtCmd.getVar("output").equals("XML")) {
                            System.out.println(getXML(ecomAdminBean.getClientByname(name)));
                        } else {
                            System.out.println(getText(ecomAdminBean.getClientByname(name)));                      
                        }
                        break;} 
                   default:
                    //res.append(_context.returnCode(ex.toString(), RESULT_ACTION.FAILED));
                    System.out.println("Error with customer manipulation");
                    break;
            }
    }
        }


    @SuppressWarnings("CallToThreadDumpStack")
        public String getXML (List<Customers> lesClients){
        String xmlString = "";
            try {
                // Create Document factory
                DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
                // Create document
                DocumentBuilder constructeur = fabrique.newDocumentBuilder();
                // Read a file XML with DOM
                File xml = new File("C:/Users/SOGOBA/Documents/NetBeansProjects/StoreEcom/StoreEcom-app-client/src/java/storeecom/XMLDocument.xml");
                Document document = constructeur.parse(xml);
                // Cr�ation de l'arborescence du DOM
                Element racine = document.getDocumentElement();
                racine.appendChild(document.createComment("La liste des clients de nos boutiques"));
                // Get all customers
                for (Customers cust : lesClients) {
                    Element client = document.createElement("Customer");
                    client.setAttribute("id", cust.getIdCustomer().toString());
                    racine.appendChild(client);
                    Element name = document.createElement("name");
                    name.setTextContent(cust.getName());
                    client.appendChild(name);
                    Element firsName = document.createElement("firsName");
                    firsName.setTextContent(cust.getFistName());
                    client.appendChild(firsName);
                    Element adress = document.createElement("adress");
                    adress.setTextContent(cust.getAdress());
                    client.appendChild(adress);
                    Element mail = document.createElement("mail");
                    mail.setTextContent(cust.getMail());
                    client.appendChild(mail);
                    Element cmp = document.createElement("account");
                    cmp.setTextContent(cust.getIdAccountFk().getIdAccount());
                    client.appendChild(cmp);
                }
                DOMSource domSource = new DOMSource(document);
                StringWriter writer = new StringWriter();
                StreamResult result = new StreamResult(writer);
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer transformer = tf.newTransformer();
                transformer.transform(domSource, result);
                xmlString = writer.toString();
            } catch (IOException | ParserConfigurationException ex) {
                Logger.getLogger(CustomersCommand.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return xmlString;

        }

    

    public String getText(List<Customers> lesClients) {
        String textString = "List of all customers \n";
        for (Customers cust : lesClients) {
            textString += "Id Client : " + cust.getIdCustomer() + "Name : " + cust.getName() + "FirstName : " + cust.getFistName() + "Adress : " + cust.getAdress() + "Mail : " + cust.getMail() + "\n";
        }
        return textString;
    }
}
